package com.assembly.videolist.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.PixelFormat
import android.graphics.SurfaceTexture
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.*
import android.view.View.OnTouchListener
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.NestedScrollView
import com.aliyun.player.AliPlayer
import com.aliyun.player.AliPlayerFactory
import com.aliyun.player.IPlayer
import com.aliyun.player.bean.InfoCode
import com.aliyun.player.nativeclass.PlayerConfig
import com.aliyun.player.source.UrlSource
import com.assembly.videolist.R
import com.assembly.videolist.ext.e
import com.assembly.videolist.utils.ScreenUtil
import kotlinx.android.synthetic.main.title_layout_back.*
import kotlinx.android.synthetic.main.video_window_layout.*
import kotlin.math.abs


/**
 * descrition:
 */
class VideoDetailWindowActivity : AppCompatActivity(), OnTouchListener {
    private val urlPath =
        "https://index.jwell56.com/opt/image/media/20220606/20220606133705_219.mp4"
    private val REQUEST_OVERLAY_CODE = 1

    val mWindowManager by lazy { (getSystemService(WINDOW_SERVICE) as WindowManager) }

    private val wmParams by lazy { getParams() }
    val layoutParams by lazy { initTopParams() }
    lateinit var mFloatLayout: View

    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private var mTouchStartX = 0
    private var mTouchStartY = 0

    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private var mStartX = 0
    private var mStartY = 0

    //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
    private var isMove = false
    var isShow = false

    /**
     * 播放器
     */
//    var aliyunListPlayer: AliListPlayer? = null

    //创建播放器
//    var aliyunVodPlayer: AliPlayer?=null
    //创建播放器
    var aliyunFloatPlayer: AliPlayer? = null

    /**
     * 是否暂停
     */
    private var mIsPause = false
    var floatTextureview: TextureView? = null
    var ivPlayIcon: ImageView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.video_window_layout)
        requestOverlayPermission()
        scrollViewContent.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
//            Log.e("video", "滑动位置  scrollY:$scrollY  oldScrollY:$oldScrollY")
            if (scrollY > 600) {
                showDialogVideo()
            } else if (scrollY < 600) {
                showTopVideo()
            }
        }
        )
        initPlayer()
        initFloatView()
        initListener()
        initPlayerView()
        initData()

    }

    /**
     * 初始化播放器
     */
    private fun initPlayer() {
//        aliyunListPlayer = AliPlayerFactory.createAliListPlayer(this)
//        //设置预加载个数。总共加载的个数为： 1 + count*2。
//        aliyunListPlayer!!.setPreloadCount(2)
//        aliyunListPlayer!!.isLoop = true
//        aliyunListPlayer!!.scaleMode = IPlayer.ScaleMode.SCALE_ASPECT_FILL
//        val config: PlayerConfig = aliyunListPlayer!!.config
//        config.mClearFrameWhenStop = true
//        aliyunListPlayer!!.config = config

        aliyunFloatPlayer = AliPlayerFactory.createAliPlayer(this)
        aliyunFloatPlayer!!.isLoop = true
        aliyunFloatPlayer!!.scaleMode = IPlayer.ScaleMode.SCALE_ASPECT_FILL
        val config: PlayerConfig = aliyunFloatPlayer!!.config
        config.mClearFrameWhenStop = true
        aliyunFloatPlayer!!.config = config
    }


    private fun initFloatView() {
        mFloatLayout = View.inflate(this, R.layout.view_floating_window, null)
        // 悬浮窗关闭
        mFloatLayout.findViewById<View>(R.id.x_image).setOnClickListener {
            mWindowManager.removeView(mFloatLayout)
        }

        floatTextureview = mFloatLayout.findViewById(R.id.videoTextureview)

        mFloatLayout.setOnTouchListener(this)
    }

    private fun initListener() {
        floatTextureview?.setOnClickListener {
            if (mIsPause) {
                resumePlay()
            } else {
                pausePlay()
            }
        }
        back_image.setOnClickListener {
            finish()
        }
    }


    /**
     * 初始化播放界面
     */
    var currentProgress: Long = 0
    private fun initPlayerView() {
        floatTextureview?.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(
                surfaceTexture: SurfaceTexture,
                width: Int,
                height: Int
            ) {
                val mSurface = Surface(surfaceTexture)
                if (aliyunFloatPlayer != null) {
                    aliyunFloatPlayer!!.setSurface(mSurface)
                    aliyunFloatPlayer!!.redraw()
                }
            }

            override fun onSurfaceTextureSizeChanged(
                surface: SurfaceTexture,
                width: Int,
                height: Int
            ) {
                if (aliyunFloatPlayer != null) {
                    aliyunFloatPlayer!!.redraw()
                }
            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                return true
            }

            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
        }

        /**
         * 准备成功事件
         */
        aliyunFloatPlayer!!.setOnPreparedListener {
            aliyunFloatPlayer!!.start()
        }

        /**
         * 失败回调
         */
        aliyunFloatPlayer!!.setOnErrorListener { errorInfo ->
            run {
                Log.e("error", errorInfo.code.toString() + " --- " + errorInfo.msg)
            }
        }

        aliyunFloatPlayer!!.setOnInfoListener { infoBean ->
//            //播放器中的一些信息，包括：当前进度、缓存位置等等
//            val code: InfoCode = infoBean.code //信息码
//            val msg = infoBean.extraMsg //信息内容
//            val value = infoBean.extraValue //信息值
            if (infoBean.code === InfoCode.CurrentPosition) {
                //extraValue为当前播放进度，单位为毫秒
                currentProgress = infoBean.extraValue
                "当前播放进度： $currentProgress".e()
            }
            //当前进度：InfoCode.CurrentPosition
            //当前缓存位置：InfoCode.BufferedPosition

        }

    }

    private fun initData() {
//        aliyunListPlayer!!.addUrl(urlPath, "0")
//        aliyunListPlayer!!.moveTo("0")
        videoContentLayout.addView(mFloatLayout,layoutParams)


        val urlSource = UrlSource()
        urlSource.uri = urlPath
        aliyunFloatPlayer!!.setDataSource(urlSource)
        aliyunFloatPlayer!!.prepare()

    }


    /**
     *
     * 滑动到底部 显示底部浮窗
     */
    private fun showDialogVideo() {
        if (isShow) return
        isShow = true

        videoContentLayout.removeView(mFloatLayout)
        mWindowManager.addView(mFloatLayout, wmParams)
    }

    /**
     * 滑动到顶部 隐藏浮窗
     */
    private fun showTopVideo() {
        if (!isShow) return
        isShow = false
        mWindowManager.removeView(mFloatLayout)
        videoContentLayout.addView(mFloatLayout,layoutParams)
    }

    private fun getParams(): WindowManager.LayoutParams {
        val layoutParams = WindowManager.LayoutParams()
        //设置悬浮窗口类型
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
        }
        //设置悬浮窗口属性
        layoutParams.flags = (WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                or WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH)
        //设置悬浮窗口透明
        layoutParams.format = PixelFormat.TRANSLUCENT
        //设置悬浮窗口长宽数据
        layoutParams.width = 600
        layoutParams.height = 450
        //设置悬浮窗显示位置
        layoutParams.gravity = Gravity.END or Gravity.BOTTOM
        layoutParams.x = 20
        layoutParams.y = 100
        return layoutParams
    }

    private fun initTopParams():ViewGroup.LayoutParams {
        val layoutParams = videoContentLayout.layoutParams

        //设置悬浮窗口长宽数据
        layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT
        layoutParams.height = ScreenUtil.dp2px(this,200f)
        return layoutParams

    }


    private fun requestOverlayPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                val intent = Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:$packageName")
                )
                startActivityForResult(intent, REQUEST_OVERLAY_CODE)
                true
            } else {
                false
            }
        } else false
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouch(v: View?, motionEvent: MotionEvent): Boolean {
        val action = motionEvent.action
        val x = motionEvent.x.toInt()
        val y = motionEvent.y.toInt()
        when (action) {
            MotionEvent.ACTION_DOWN -> {
                isMove = false
                mTouchStartX = motionEvent.rawX.toInt()
                mTouchStartY = motionEvent.rawY.toInt()
                mStartX = x
                mStartY = y
            }
            MotionEvent.ACTION_MOVE -> {
                val mTouchCurrentX = motionEvent.rawX.toInt()
                val mTouchCurrentY = motionEvent.rawY.toInt()

//                wmParams!!.x += mTouchCurrentX - mTouchStartX
//                wmParams!!.y += mTouchCurrentY - mTouchStartY

                wmParams.x += mTouchStartX - mTouchCurrentX
                wmParams.y += mTouchStartY - mTouchCurrentY

                mWindowManager?.updateViewLayout(mFloatLayout, wmParams)
                mTouchStartX = mTouchCurrentX
                mTouchStartY = mTouchCurrentY
                val deltaX = (x - mStartX).toFloat()
                val deltaY = (y - mStartY).toFloat()

                if (abs(deltaX) >= 5 || abs(deltaY) >= 5) {
                    isMove = true
                }
            }
            MotionEvent.ACTION_UP -> {
            }
            else -> {
            }
        }
        //如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
        return isMove
    }

    /**
     * 暂停播放
     */
    private fun pausePlay() {
        mIsPause = true
        if (aliyunFloatPlayer != null) {
            if (ivPlayIcon != null) {
                ivPlayIcon!!.visibility = View.VISIBLE
            }

            aliyunFloatPlayer!!.pause()
        }
    }

    /**
     * 恢复播放
     */
    private fun resumePlay() {
        mIsPause = false
        if (aliyunFloatPlayer != null) {
            if (ivPlayIcon != null) {
                ivPlayIcon!!.visibility = View.GONE
            }
            aliyunFloatPlayer!!.start()
        }
    }

    /**
     * 销毁
     */
    private fun destroy() {
        if (aliyunFloatPlayer != null) {
            aliyunFloatPlayer!!.stop()
            aliyunFloatPlayer!!.release()
        }

        if (aliyunFloatPlayer != null) {
            aliyunFloatPlayer!!.stop()
            aliyunFloatPlayer!!.release()
        }
    }

    override fun onPause() {
        super.onPause()
        pausePlay()
    }

    override fun onResume() {
        super.onResume()
        resumePlay()
    }

    override fun onDestroy() {
        super.onDestroy()
        destroy()
    }


}